/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.annotation;

import org.springframework.aop.config.AopConfigUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * Registers an {@link org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
 * AnnotationAwareAspectJAutoProxyCreator} against the current {@link BeanDefinitionRegistry}
 * as appropriate based on a given @{@link EnableAspectJAutoProxy} annotation.
 * 根据给定的 @{@link EnableAspectJAutoProxy} 注释，根据当前 {@link BeanDefinitionRegistry}
 * 注册一个 {@link org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
 * AnnotationAwareAspectJAutoProxyCreator}。
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.1
 * @see EnableAspectJAutoProxy
 */
//实现ImportBeanDefinitionRegistrar接口的类可以通过@Import注入Bean (参见 study-imooc/61-spring-annotation)
/**
 * AnnotationConfigApplicationContext() -> refresh() ->
 * 第5步：invokeBeanFactoryPostProcessors(beanFactory) 完成对Bean的扫描（@Import(ImportBeanDefinitionRegistrar实现类)），
 *       将class变成beanDefinition存在beanDefinitionMap中.
 *          -> PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
 *             -> PostProcessorRegistrationDelegate # invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
 *                -> ConfigurationClassPostProcessor # postProcessBeanDefinitionRegistry(registry); //ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
 *                   -> ConfigurationClassPostProcessor # processConfigBeanDefinitions(registry)
 *                      -> ConfigurationClassBeanDefinitionReader # loadBeanDefinitions(configClasses) // configClasses 里面存放的是 import 注入类返回数组对象中的 bean
 *                         -> ConfigurationClassBeanDefinitionReader # loadBeanDefinitionsForConfigurationClass(configClass.getImportedResources()) //getImportedResources()获取所有的 ImportBeanDefinitionRegistrar 资源
 *                            -> ConfigurationClassBeanDefinitionReader # loadBeanDefinitionsFromRegistrars() 遍历 ImportBeanDefinitionRegistrar 调用 registerBeanDefinitions() 方法
 *                               -> 进入到 AspectJAutoProxyRegistrar#registerBeanDefinitions() 中注册 AnnotationAwareAspectJAutoProxyCreator Bean
 *
 * AnnotationConfigApplicationContext() -> refresh() ->
 * 第11步：finishBeanFactoryInitialization() 初始化剩下的单实例（非延迟） 这里面触发 getBean() -> createBean()
 *        -> doCreateBean()
 *           -> initializeBean()
 *              -> applyBeanPostProcessorsAfterInitialization() 中遍历所有的 BeanPostProcessor 调用
 *                 -> postProcessAfterInitialization()
 *                    -> 进入 AnnotationAwareAspectJAutoProxyCreator，由于这是 BeanPostProcessor，当 Spring 加载 Bean 时会在实例化之后回调：postProcessAfterInstantiation() 方法
 *                        -> AbstractAutoProxyCreator # postProcessBeforeInstantiation() 方法
 */
// 实现了 ImportBeanDefinitionRegistrar接口 的类，将被 @Import 引入，根据其实现方法注册bean
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
	 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
	 * {@code @Configuration} class.
	 * 根据导入 {@code @Configuration} 类上的 @{@link EnableAspectJAutoProxy#proxyTargetClass()}
	 * 属性的值注册、升级和配置 AspectJ 自动代理创建者。
	 */
	/**
	 * 把所有需要添加到容器中的bean；调用 BeanDefinitionRegistry.registerBeanDefinition 手工注册进来
	 * @param importingClassMetadata 当前类的注解信息
	 * @param registry BeanDefinition注册类
	 */
	// 在 registerBeanDefinitions() 方法中注册所需要的 bean
	@Override
	public void registerBeanDefinitions(
			AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

		// 注册 AnnotationAwareAspectJAutoProxyCreator.class , 它也是 BeanPostProcessor 类型。
		// 在 refresh() -> 第11步：finishBeanFactoryInitialization() 中创建 doCreateBean 时应用这个注册的后置处理器处理实例化后的bean。
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

		// 解析注解EnableAspectJAutoProxy
		AnnotationAttributes enableAspectJAutoProxy =
				AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		// 引用自@Import(MapperScannerRegistrar.class)里面的,等价
//		AnnotationAttributes enableAspectJAutoProxy = AnnotationAttributes
//				.fromMap(importingClassMetadata.getAnnotationAttributes(EnableAspectJAutoProxy.class.getName()));

		// 判断配置类 AppConfig 是否加了 @EnableAspectJAutoProxy 注解
		if (enableAspectJAutoProxy != null) {
			// 默认是 false 指用 jdk 动态代理,值为 true 则开启 cglib 代理
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			// 如果设置了 exposeProxy=true 就强制使用
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				// 暴露代理的bean
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}

}
